var couponSelect = Vue.component('coupon-select', {
    template: `
    <div class="compontent-coupon">
        <div class="item-content">
            <div class="item-inner" @click.prevent="coupon_popup=!coupon_popup">
                <div class="float-left title">
                    优惠券
                </div>
                <div class="float-right">
                    <span v-if="list.length==0">暂无优惠劵</span>
                    <span v-else-if="selected_coupon.length==0"><i class="fa fa-chevron-right"></i></span>
                    <span v-else>已选择</span>
                </div>
            </div>
        </div>
        <div class="line" v-if="selected_coupon.length>0"></div>
        <!--
        <div class="item-content">
            <div class="item-inner">
                <div class="item-title">
                    <b>优惠券:</b>
                    <span class="color-orange" v-if="selected_coupon.length==0">无选择优惠劵</span>
                    
                </div>
                <i class="fa fa-arrow-right" @click.prevent="openList" v-show="!coupon_popup"></i>
                <i class="fa fa-times" @click.prevent="closeList" v-show="coupon_popup"></i>
            </div>
        </div>
        -->
        <div class="coupon-list">
            <template v-for="(v,i) in selected_coupon">
                <div>
                    <label class="label-checkbox item-content">
                        <div class="item-inner">
                            <div class="item-title">
                            {{i+1}}.
                            {{v.title}}
                            </div>
                        </div>
                    </label>
                </div>
            </template>
        </div>
        <div>
            <div class="line"></div>
        </div>
        <div class="coupon-list" v-show="coupon_popup">
            <template v-for="v in list">
                <div>
                    <label class="label-checkbox item-content" :class="{'disabled':v.disabled}">
                        <input type="checkbox" :value="v" v-model="selected_coupon" :disabled="v.disabled" :key="v.id">
                        <div class="item-media">
                            <i class="icon icon-form-checkbox"></i>
                        </div>
                        <div class="item-inner">
                            <div class="item-title">{{v.title}}
                            </div>
                        </div>
                    </label>
                </div>
            </template>
            <div class="item-content" v-if="list.length==0">
                <div class="item-inner">
                    <div class="item-title">
                        暂无优惠劵
                    </div>
                </div>
            </div>
        </div>
        <div v-show="coupon_popup">
            <div class="line"></div>
        </div>

    </div>
    `,
    props: {
        freight:{
            type:Number,
            default:0
        },
        freightFreePrice: {
            type: Number,
            defautl: 0
        },
        listCart: {
            type: Array,
            defautl: []
        }
    },
    data() {
        return {
            list: [], //优惠劵列表
            list_cart:[],//货物列表
            o_total_price:0,
            freight_coupon:0,
            total_coupon:0,

            coupon_popup: false, //打开优惠劵列表

            selected_coupon: [],
            selected_coupon_ids:[]
        }
    },
    filters: {
        couponStr(v) {
            var self = this;
            var title = v.title;
            switch(v.type){
                case 1:
                if(v.satisfy){
                    title = '满'+v.satisfy+'总价减'+v.paValue+'元（最多减至0元）';
                } else {
                    title = '总价减'+v.paValue+'元（最多减至0元）';
                }
                break;
                case 2:
                if(v.satisfy){
                    title = '满'+v.satisfy+'运费减'+v.paValue+'元（最多减至运费0元）';
                } else {
                    title = '运费减'+v.paValue+'元（最多减至运费0元）';
                }
                break;
                case 3:
                if(v.satisfy){
                    title = v.title + '仅需'+v.paValue +'元购买';
                } else {
                    title = v.title;
                }
                break;
                default:
                title = '优惠劵错误';

            }
            return title;
        },
    },
    methods: {
        init() {
            var self = this;
            self.getList();
        },
        getList() {
            var self = this;
            ajax.queryCoupon({
                type: 'post',
                param: {
                    token: localStorage.token,
                    status:0
                },
                cb(data) {
                    if (data.datalist && data.datalist.length > 0) {
                        self.list = _.sortBy(data.datalist, [
                            function(o) {
                                return o.type; 
                            },
                            function(o) {
                                return o.goods; 
                            }
                        ]).map(function(v){
                            v.selected = false;
                            v.disabled = false;
                            if(v.type==2){
                                v.max = 1;
                            }
                            if(v.type==3){
                                v.max = 1;
                            }
                            if(v.type==1){
                                v.max = 1;
                                v.exclusive = [3]
                            }
                            return v;
                        }).filter((v)=>{
                            return v.type!=2&&v.type!=0;
                        });
                    }
                }
            });
        },
        openList() {
            var self = this;
            // self.coupon_popup = true;
            self.$emit('openlist');
        },
        closeList() {
            var self = this;
            // self.coupon_popup = false;
            self.$emit('closelist');
        },
        isValDate(st,et){
            var self = this;
            var nt = (new Date()).getTime();
            if (st&&nt<st) {
                return false;
            }
            if (et&&nt>et) {
                return false;
            }
            return true;
        },
        setCouponList() {
            var self = this;
            var exclusive = [];
            var max_coupon = {};
            var selected_coupon_ids = [];
            self.total_coupon = self.o_total_price;
            self.freight_coupon = self.freight;
            self.list_cart = self.list_cart.map((o)=>{
                o.totalCouponPrice = o.totalPrice;
                return o;
            })
            self.selected_coupon.forEach(function(v){
                var inner_exclusive = []
                if(v.exclusive){
                    inner_exclusive = v.exclusive;
                }
                inner_exclusive.forEach(function(iev){
                    if(exclusive.indexOf(exclusive)==-1){
                        exclusive.push(iev);
                    }
                })
                if(v.max!=null){
                    if(max_coupon[v.type]){
                        max_coupon[v.type].push(v.id);
                    } else {
                        max_coupon[v.type] = [v.id]
                    }
                }
                if(v.type==2){
                    self.freight_coupon = self.freight - v.paValue;
                }
                if(v.type==1){
					if( v.satisfy && v.satisfy <= self.total_coupon ){
						self.total_coupon = self.total_coupon-v.paValue;
					}
                    if(self.total_coupon<0){
                        self.total_coupon = 0;   
                    }
                }
                if(v.type==3&&v.goods){
                    var good = _.find(self.list_cart,function(co){
                        return co.fkSourceId == v.goods;
                    });
                    var less = good.preferentialPrice - v.paValue;
                    good.totalCouponPrice = parseFloat((good.totalCouponPrice - less).toFixed(2));
                }
                selected_coupon_ids.push(v.id)
            });
            self.selected_coupon_ids = selected_coupon_ids;

            self.list = self.list.map(function(v){
                var disabled = false;
                if(self.isValDate(v.startTime,v.endTime)==false){
                    disabled = true;
                }
                var in_cart = _.find(self.list_cart,function(o){
                    return o.fkSourceId == v.goods;
                });
                if(in_cart===undefined&&v.type==3){
                    disabled = true;
                }
                if(exclusive.indexOf(v.type)!=-1){
                    disabled = true;
                }
   
                if(v.type==2&&self.o_total_price>self.freightFreePrice){
                    disabled = true;
                }
                if(max_coupon[v.type]){
                    if(max_coupon[v.type].length==v.max&&max_coupon[v.type].indexOf(v.id)==-1){
                        disabled = true;
                    }
                }
                v.disabled = disabled;
                return v;
            });
        }
    },
    watch: {
        coupon_popup(v){
            var self = this;
            if(v){
                self.closeList();
                self.list_cart = self.listCart.map(function(o){
                    o.totalCouponPrice = o.totalPrice;
                    return o;
                });
                self.freight_coupon = self.freight;
                self.o_total_price = _.sumBy(self.list_cart,function(o){
                    return parseFloat((o.preferentialPrice * o.qty).toFixed(2));
                })
                self.setCouponList();
            }else{
                self.openList();
            }
        },
        selected_coupon(v) {
            var self = this;
            self.setCouponList();
            var resultObj = {
                listCart:self.list_cart,
                coupons:self.selected_coupon_ids,
                selectCoupons:self.selected_coupon.map((o)=>{
                    var obj = {
                        id:o.id,
                        paValue:o.paValue,
                        type:o.type,
                        title:o.title,
                        satisfy:o.satisfy,
                        goods:o.goods
                    }
                    return obj;
                })
            };
            if(self.freight_coupon!=self.freight){
                resultObj.freightCoupon = self.freight_coupon;
            }
            if(self.total_coupon!=self.o_total_price){
                resultObj.totalCoupon = self.total_coupon;
            }
            
            self.$emit('couponchg', resultObj); 
        }
    },
    mounted() {
        var self = this;
        self.init();
    }
});